package org.jeecg.modules.hc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.hc.controller.dao.CustomExportXlsDao;
import org.jeecg.modules.hc.entity.*;
import org.jeecg.modules.hc.enums.HcMerchantSettlementTypeEnum;
import org.jeecg.modules.hc.enums.HcOrderStateEnum;
import org.jeecg.modules.hc.mapper.*;
import org.jeecg.modules.hc.service.IHcCompanyFoodOrderService;
import org.jeecg.modules.hc.service.IHcCompanyInfoService;
import org.jeecg.modules.hc.service.IHcCompanyPickupAddressService;
import org.jeecg.modules.hc.service.IHcMerchantService;
import org.jeecg.modules.hc.service.impl.pojo.CustomExportXlsTotalPojo;
import org.jeecg.modules.hc.utils.DateTimeUtils;
import org.jeecg.modules.hc.utils.HcUtils;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.Collator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Description: 企业订餐订单
 * @Author: jeecg-boot
 * @Date:   2023-07-11
 * @Version: V1.0
 */
@Service
public class HcCompanyFoodOrderServiceImpl extends ServiceImpl<HcCompanyFoodOrderMapper, HcCompanyFoodOrder> implements IHcCompanyFoodOrderService {

    @Resource
    private HcCompanyFoodOrderMapper hcCompanyFoodOrderMapper;
    @Resource
    private HcCompanyDepartmentMapper hcCompanyDepartmentMapper;
    @Resource
    private HcCompanyFoodListMapper hcCompanyFoodListMapper;
    @Resource
    private HcCompanyInfoMapper hcCompanyInfoMapper;
    @Resource
    private HcMerchantMapper hcMerchantMapper;
    @Resource
    private HcCompanyDetailMapper hcCompanyDetailMapper;
    @Resource
    private HcCompanyPickupAddressMapper hcCompanyPickupAddressMapper;
    @Resource
    private HcCompanyMerchantSettingMapper hcCompanyMerchantSettingMapper;
    @Resource
    private HcCompanyMerchantSettlementMapper hcCompanyMerchantSettlementMapper;

    @Autowired
    private IHcCompanyInfoService hcCompanyInfoService;
    @Autowired
    private IHcCompanyPickupAddressService hcCompanyPickupAddressService;

    @Autowired
    private IHcMerchantService hcMerchantService;

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;


    @Override
    public Map<String,Object> getGlobalMerchantOrderList(String companyId) {
        final Long[] totalSaleCount = {(long) 0};
        //获取所有企业
        LambdaQueryWrapper<HcCompanyInfo> companyInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(companyId)){
            companyInfoLambdaQueryWrapper.eq(HcCompanyInfo::getId,companyId);
        }
        List<String> companyIdList = hcCompanyInfoMapper.selectList(companyInfoLambdaQueryWrapper).stream().map(HcCompanyInfo::getId).collect(Collectors.toList());
        List<HcMerchant>  dataList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(companyIdList)){
            companyIdList.forEach(h -> {
                //获取企业对应的商户
                List<HcCompanyDetail> hcCompanyDetails = hcCompanyDetailMapper.selectList(new LambdaQueryWrapper<HcCompanyDetail>().eq(HcCompanyDetail::getCompanyId, h).orderByDesc(HcCompanyDetail::getCreateTime).last("limit 1"));
                if (CollectionUtils.isNotEmpty(hcCompanyDetails)){
                    HcCompanyDetail hcCompanyDetail = hcCompanyDetails.get(0);
                    if (StringUtils.isNotBlank(hcCompanyDetail.getListingStoreIds())){
                        // 获取当前日期
                        LocalDate today = LocalDate.now();
                        // 获取昨天的日期
                        LocalDate yesterday = today.minusDays(1);
                        // 创建 LocalTime 对象表示 19:00
                        LocalTime specificTime = LocalTime.of(19, 0);
                        // 获取昨天的 19:00
                        LocalDateTime yesterdaySpecificTime = LocalDateTime.of(yesterday, specificTime);
                        // 获取今天的 19:00
                        LocalDateTime todaySpecificTime = LocalDateTime.of(today, specificTime);
                        // 创建日期时间格式化器
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        // 格式化日期时间为字符串
                        String yesterdayFormatted = yesterdaySpecificTime.format(formatter);
                        String todayFormatted = todaySpecificTime.format(formatter);

                        List<String> merchantIds = Arrays.asList(hcCompanyDetail.getListingStoreIds().split(","));
                        merchantIds.forEach(m -> {
                            HcMerchant hcMerchant = hcMerchantMapper.selectById(m);
                            if (null != hcMerchant){
                                //商户订单数量
                                long count = hcCompanyFoodOrderMapper.selectList(new LambdaQueryWrapper<HcCompanyFoodOrder>()
                                        .eq(HcCompanyFoodOrder::getDetailsId, hcCompanyDetail.getId())
                                        .eq(HcCompanyFoodOrder::getMerchantId,m)
                                        .between(HcCompanyFoodOrder::getCreateTime,yesterdayFormatted,todayFormatted))
                                        .stream().filter(c-> c.getState().equals(HcOrderStateEnum.UNCOMPLETED)).map(HcCompanyFoodOrder::getOrderNum).distinct().collect(Collectors.toList()).size();
                                hcMerchant.setMerchantSaleCount(count);
                                totalSaleCount[0] = totalSaleCount[0] + count ;
                                dataList.add(hcMerchant);
                            }
                        });
                    }
                }
            });
            dataList.sort(new Comparator<HcMerchant>() {
                @Override
                public int compare(HcMerchant o1, HcMerchant o2) {
                    return o2.getMerchantSaleCount().compareTo(o1.getMerchantSaleCount());
                }
            });
        }
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("totalSaleCount",totalSaleCount[0]);
        dataMap.put("merchantData",dataList);
        return dataMap;
    }

    @Override
    public HcMerchant getGlobalMerchantOrderDetailsList(String merchantId, String companyId) {
        HcMerchant result = hcMerchantMapper.selectById(merchantId);
        List<HcOrderDetailed> orderDetailedList = new ArrayList<>();

        LambdaQueryWrapper<HcCompanyFoodOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(companyId)){
            orderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getCompanyId, companyId);
        }
        orderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getMerchantId, merchantId)
                .eq(HcCompanyFoodOrder::getState, HcOrderStateEnum.UNCOMPLETED);
        List<HcCompanyFoodOrder> companyFoodOrders = hcCompanyFoodOrderMapper.selectList(orderLambdaQueryWrapper).stream().filter(c -> !c.getState().equals(HcOrderStateEnum.CANCELED)).collect(Collectors.toList());
        for (HcCompanyFoodOrder order : companyFoodOrders) {
            JSONObject foodInfo = JSONObject.parseObject(order.getFoodInfo());
            //商品数量
            Integer foodNum = (Integer) foodInfo.get("foodNum");
            JSONObject foodObject = foodInfo.getJSONObject("food");
            HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);

            HcOrderDetailed h = new HcOrderDetailed();
            h.setTradeName(hcCompanyFoodList.getFoodName());
            h.setCommodityQuantity(foodNum);

            if (orderDetailedList.size() > 0) {
                boolean found = false;
                for (HcOrderDetailed hcOrderDetailed : orderDetailedList) {
                    if (hcOrderDetailed.getTradeName().equals(h.getTradeName())) {
                        hcOrderDetailed.setCommodityQuantity(hcOrderDetailed.getCommodityQuantity() + foodNum);
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    orderDetailedList.add(h);
                }
            } else {
                orderDetailedList.add(h);
            }
            result.setHcOrderDetailedList(orderDetailedList);
        }
        return result;
    }




    @Override
    public String customExportXls(CustomExportXlsDao customExportXlsDao) throws IOException, ParseException {
        Map<String , Object> param = new LinkedHashMap<>();
        customExportXlsDao.getFieldList().forEach( p -> {
            Map map = JSONObject.parseObject(JSONObject.toJSONString(p),Map.class);
            param.put("pickingSerialNo","取餐序号");
            param.putAll(map);
            param.put("exportState","订单状态");
        });

        //按照公司查询那一天的数据
        HcCompanyDetail hcCompanyDetails = hcCompanyDetailMapper.selectOne(new LambdaQueryWrapper<HcCompanyDetail>().eq(HcCompanyDetail::getId, customExportXlsDao.getDetailId()));
        List<String> merchantIdList = Arrays.asList(hcCompanyDetails.getListingStoreIds().split(","));
        //公司信息
        HcCompanyInfo hcCompanyInfo = hcCompanyInfoMapper.selectOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, hcCompanyDetails.getCompanyId()));
        String menuDisplayTime = hcCompanyDetails.getMenuDisplayTime();


    //        String startTime = menuDisplayTime + " 00:00:01";
        String endTime = menuDisplayTime +" 18:30:00";
        Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime);
        String startTime = DateTimeUtils.daysBefore(date, 1);
        //获取订单
        List<HcCompanyFoodOrder> companyFoodOrderList = hcCompanyFoodOrderMapper.selectList(new LambdaQueryWrapper<HcCompanyFoodOrder>()
                .eq(HcCompanyFoodOrder::getCompanyId, hcCompanyDetails.getCompanyId())
                .between(HcCompanyFoodOrder::getCreateTime, startTime, endTime));
        List<HcCompanyFoodOrder> companyFoodOrders = companyFoodOrderList.stream().filter(c -> !c.getState().equals(HcOrderStateEnum.CANCELED)).collect(Collectors.toList());
        List<HcCompanyFoodOrder> data = new ArrayList<>();
        //汇总
        BigDecimal foodAllPrice = new BigDecimal(0);
        if (CollectionUtils.isNotEmpty(companyFoodOrders)) {
            List<String> orderNums = companyFoodOrders.stream().map(HcCompanyFoodOrder::getOrderNum).distinct().collect(Collectors.toList());
            for (String s : merchantIdList) {
                for (String orderNum : orderNums) {
                    List<HcCompanyFoodOrder> orders = companyFoodOrders.stream().filter(c -> c.getOrderNum().equals(orderNum) && c.getMerchantId().equals(s)).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(orders)) {
                        for (HcCompanyFoodOrder order : orders) {
                            HcCompanyFoodOrder excelOrder = new HcCompanyFoodOrder();

                            excelOrder.setUsername(order.getUsername());
                            //取餐地址
                            String pickupAddressId = order.getPickupAddressId();
                            HcCompanyPickupAddress pickupAddress = hcCompanyPickupAddressMapper.selectOne(new LambdaQueryWrapper<HcCompanyPickupAddress>()
                                    .eq(HcCompanyPickupAddress::getId, pickupAddressId));
                            excelOrder.setPickupAddress(hcCompanyInfo.getCompanyName() + hcCompanyInfo.getCompanyAddress() + pickupAddress.getPickupAddress());
                            HcMerchant hcMerchant = hcMerchantMapper.selectOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getId, s));
                            //商户
                            excelOrder.setMerchantName(hcMerchant.getStoreName());
                            //部门
                            HcCompanyDepartment hcCompanyDepartment = hcCompanyDepartmentMapper.selectOne(new LambdaQueryWrapper<HcCompanyDepartment>().eq(HcCompanyDepartment::getId, orders.get(0).getDepartmentId()));
                            if (null != hcCompanyDepartment) {
                                excelOrder.setDepartment(hcCompanyDepartment.getDepartmentName());
                            }
                            //备注
                            excelOrder.setRemark(order.getRemark());

                            //金额  菜品
                            List<String> foodName = new ArrayList<>();

                            BigDecimal orderPrice = new BigDecimal(0);
//                            for (HcCompanyFoodOrder hcCompanyFoodOrder : orders) {
                                //价格
                                BigDecimal foodPrice = new BigDecimal(0);
                                JSONObject foodInfo = JSONObject.parseObject(order.getFoodInfo());
                                JSONObject foodObject = foodInfo.getJSONObject("food");
                                HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
                                //商品数量
                                int foodNum = (int) foodInfo.get("foodNum");
//                                // 获取 foodsSpecification 列表
//                                JSONArray foodsSpecificationArray = foodInfo.getJSONArray("foodsSpecification");
//                                // 将 JSONArray 转换为 List<String>
//                                List<HcCompanyFoodSpecifications> foodsSpecificationList = new ArrayList<>();
//                                if (foodsSpecificationArray != null) {
//                                    foodsSpecificationList = foodsSpecificationArray.toJavaList(HcCompanyFoodSpecifications.class);
//                                    if (CollectionUtils.isNotEmpty(foodsSpecificationList)){
//                                        List<String> collect = foodsSpecificationList.stream().map(f -> f.getSpecificationName()).collect(Collectors.toList());
//                                        foodName.add(hcCompanyFoodList.getFoodName() + "( " + Joiner.on(", ").join(collect) + " ) * " + foodNum);
//                                    }
//                                } else {
//                                    foodName.add(hcCompanyFoodList.getFoodName() + " * " + foodNum);
//                                }

                                // 获取 foodsSpecification 列表
                                JSONArray foodsSpecificationArray = foodInfo.getJSONArray("foodsSpecification");
                                List<HcCompanyFoodSpecifications> foodsSpecificationList = new ArrayList<>();

                                if (CollectionUtils.isNotEmpty(foodsSpecificationArray)) {
                                    foodsSpecificationList = foodsSpecificationArray.toJavaList(HcCompanyFoodSpecifications.class);
                                }

                                if (CollectionUtils.isNotEmpty(foodsSpecificationList) || null!=foodsSpecificationList) {
                                    List<String> collect =  new ArrayList<>();
                                    foodsSpecificationList.forEach( f -> {
                                        if (null!=f){
                                            collect.add(f.getSpecificationName());
                                        }
                                    });
                                    if (CollectionUtils.isNotEmpty(collect)){
                                        foodName.add(hcCompanyFoodList.getFoodName() + "( " + Joiner.on(", ").join(collect) + " ) * " + foodNum);
                                    }else {
                                        foodName.add(hcCompanyFoodList.getFoodName() + " * " + foodNum);
                                    }
                                } else {
                                    foodName.add(hcCompanyFoodList.getFoodName() + " * " + foodNum);
                                }

                                if ((hcCompanyFoodList.getSalePrice() == null ? new BigDecimal(0) : hcCompanyFoodList.getSalePrice()).compareTo(new BigDecimal(0)) == 0) {
                                    //获取门店价格
                                    HcCompanyMerchantSetting companyMerchantSetting = hcCompanyMerchantSettingMapper.selectOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
                                            .eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
                                            .eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
                                    if (null == companyMerchantSetting) {
                                        companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
                                    }
                                    if (companyMerchantSetting.getSalePrice() == null || companyMerchantSetting.getSalePrice().compareTo(new BigDecimal(0)) == 0) {
                                        //获取企业合作价格
                                        foodPrice = foodPrice.add(hcCompanyInfo.getCompanyPrice().multiply(new BigDecimal(foodNum)));
                                    } else {
                                        foodPrice = foodPrice.add(companyMerchantSetting.getSalePrice().multiply(new BigDecimal(foodNum)));
                                    }
                                } else {
                                    foodPrice = foodPrice.add(hcCompanyFoodList.getSalePrice().multiply(new BigDecimal(foodNum)));
                                }
                                orderPrice = orderPrice.add(foodPrice);
//                            }
                            foodAllPrice = foodAllPrice.add(orderPrice);
                            //总价格
                            excelOrder.setCost(orderPrice);
                            //菜品名
                            excelOrder.setFoodsName(foodName.size() > 1 ? Joiner.on("+").join(foodName) : foodName.get(0));
                            excelOrder.setSubmissionTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getCreateTime()));
                            //状态
                            excelOrder.setExportState(order.getState().getName().equals("已下单") ? "未完成" : order.getState().getName());
                            //状态
                            excelOrder.setPickingSerialNo(order.getPickingSerialNo());
                            data.add(excelOrder);
                        }
                    }
                }
            }

        }

        data.sort(new Comparator<HcCompanyFoodOrder>() {
            @Override
            public int compare(HcCompanyFoodOrder o1, HcCompanyFoodOrder o2) {
                return o1.getMerchantName().compareTo(o2.getMerchantName());
            }
        });

        // 创建工作簿和工作表
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");
        // 设置中文样式
        Font chineseFont = workbook.createFont();
        chineseFont.setFontName("宋体");
        chineseFont.setBold(true);
        chineseFont.setColor(IndexedColors.BLACK.getIndex());
        CellStyle chineseCellStyle = workbook.createCellStyle();
        chineseCellStyle.setFont(chineseFont);
        // 创建数据样式
        CellStyle dataCellStyle = workbook.createCellStyle();
        dataCellStyle.setBorderTop(BorderStyle.THIN);
        dataCellStyle.setBorderBottom(BorderStyle.THIN);
        dataCellStyle.setBorderLeft(BorderStyle.THIN);
        dataCellStyle.setBorderRight(BorderStyle.THIN);

        // 创建表头
        Row headerRow = sheet.createRow(0);
        Set<String> fields = param.keySet();
        int colNum = 0;

        // 添加序号列
        Cell counterCell = headerRow.createCell(colNum++);
        counterCell.setCellValue("序号");
        counterCell.setCellStyle(chineseCellStyle);

        for (String value : fields) {
            Cell cell = headerRow.createCell(colNum++);
            cell.setCellValue((String) param.get(value));
            cell.setCellStyle(chineseCellStyle); // 应用中文样式
        }

        //数据填充
        int rowNum = 1;
        AtomicInteger counter = new AtomicInteger(1);
        for (HcCompanyFoodOrder order : data) {
            //创建每行数据
            Row dataRow = sheet.createRow(rowNum++);
            // 设置序号列的值
            Cell counterCellData = dataRow.createCell(0);
            counterCellData.setCellValue(counter.getAndIncrement());
            counterCellData.setCellStyle(dataCellStyle);
            //从第2列开始
            AtomicInteger cellNum = new AtomicInteger(1);
            //遍历属性，填充表格
            fields.forEach(l -> {
                try {
                    Field studentField = HcCompanyFoodOrder.class.getDeclaredField(l.trim());
                    studentField.setAccessible(true);
                    Object o =studentField.get(order);
                    // 创建单元格并填充值
                    Cell cell = dataRow.createCell(cellNum.getAndIncrement());
                    cell.setCellValue(o != null ? o.toString() : "");
                    cell.setCellStyle(dataCellStyle); // 应用数据样式

                    // 自动调整列宽
                    sheet.autoSizeColumn(cellNum.get() - 1);
                    // 获取自动调整后的列宽
                    int currentWidth = sheet.getColumnWidth(cellNum.get() - 1);

                    // 添加额外的字符宽度
                    int extraWidth = 200 * 2; // 设置额外的字符宽度
                    int finalWidth = currentWidth + extraWidth;

                    // 设置列宽
                    sheet.setColumnWidth(cellNum.get() - 1, finalWidth);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }

        //创建合计行数据
        Row dataAllRow = sheet.createRow(data.size()+1);
        Cell cell0 = dataAllRow.createCell(0);
        cell0.setCellValue("合计：");
        cell0.setCellStyle(dataCellStyle);

        //从第2列开始
        AtomicInteger cellAllNum = new AtomicInteger(1);
        //遍历属性，填充表格
        BigDecimal finalFoodAllPrice = foodAllPrice;
        fields.forEach(l -> {
            try {
                Field studentField = HcCompanyFoodOrder.class.getDeclaredField(l.trim());
                studentField.setAccessible(true);
                Object o =studentField.get(new HcCompanyFoodOrder().setCost(finalFoodAllPrice));
                // 创建单元格并填充值
                Cell cell = dataAllRow.createCell(cellAllNum.getAndIncrement());
                cell.setCellValue(o != null ? o.toString() : "");
                cell.setCellStyle(dataCellStyle); // 应用数据样式

                // 自动调整列宽
                sheet.autoSizeColumn(cellAllNum.get() - 1);
                // 获取自动调整后的列宽
                int currentWidth = sheet.getColumnWidth(cellAllNum.get() - 1);

                // 添加额外的字符宽度
                int extraWidth = 200 * 2; // 设置额外的字符宽度
                int finalWidth = currentWidth + extraWidth;

                // 设置列宽
                sheet.setColumnWidth(cellAllNum.get() - 1, finalWidth);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        Sheet sheet1 = workbook.createSheet("部门统计");
        Map<String,String> sheet1FieldMap = new LinkedHashMap<>();
        sheet1FieldMap.put("departmentName","部门名称");
        sheet1FieldMap.put("totalOrder","合计份数");
        sheet1FieldMap.put("totalAmount","合计金额");


        //获取公司下的部门
        LambdaQueryWrapper<HcCompanyDepartment> departmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        departmentLambdaQueryWrapper.eq(HcCompanyDepartment::getCompanyId,hcCompanyDetails.getCompanyId());
        List<HcCompanyDepartment> hcCompanyDepartments = hcCompanyDepartmentMapper.selectList(departmentLambdaQueryWrapper);

        // 使用 LinkedHashMap 保持插入顺序
        Map<String, CustomExportXlsTotalPojo> orderedMap = new LinkedHashMap<>();

        Long totalOrder =(long)0;
        BigDecimal totalAmount = new BigDecimal("0");
        for (HcCompanyDepartment hcCompanyDepartment : hcCompanyDepartments) {
            CustomExportXlsTotalPojo cus = new CustomExportXlsTotalPojo();

            //部门
            LambdaQueryWrapper<HcCompanyDepartment> hcCompanyDepartmentLambdaQueryWrapper =new LambdaQueryWrapper<>();
            hcCompanyDepartmentLambdaQueryWrapper.eq(HcCompanyDepartment::getId,hcCompanyDepartment.getId());
            HcCompanyDepartment companyDepartment = hcCompanyDepartmentMapper.selectOne(hcCompanyDepartmentLambdaQueryWrapper);
            cus.setDepartmentName(companyDepartment.getDepartmentName());

            LambdaQueryWrapper<HcCompanyFoodOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getDepartmentId,hcCompanyDepartment.getId())
                    .eq(HcCompanyFoodOrder::getState,HcOrderStateEnum.COMPLETED)
                    .between(HcCompanyFoodOrder::getCreateTime,startTime,endTime);
            List<HcCompanyFoodOrder> hcCompanyFoodOrders = hcCompanyFoodOrderMapper.selectList(orderLambdaQueryWrapper);
            List<String> orderNumList = hcCompanyFoodOrders.stream().map(HcCompanyFoodOrder::getOrderNum).distinct().collect(Collectors.toList());
            //部门总花费
            BigDecimal departmentTotalAmount = new BigDecimal("0");
            //总数量
            int departmentTotalNum = 0;
            if (CollectionUtils.isNotEmpty(hcCompanyFoodOrders)){
                for (String orderNum : orderNumList) {
                    List<HcCompanyFoodOrder> orders = companyFoodOrders.stream().filter(c -> c.getOrderNum().equals(orderNum)).collect(Collectors.toList());
                    //价格
                    BigDecimal orderNumFoodCost = new BigDecimal(0);
                    //总数量
                    int orderNumTotalNum = 0;
                    BigDecimal orderPrice = new BigDecimal(0);
                    for (HcCompanyFoodOrder hcCompanyFoodOrder : orders) {
                        JSONObject foodInfo = JSONObject.parseObject(hcCompanyFoodOrder.getFoodInfo());
                        JSONObject foodObject = foodInfo.getJSONObject("food");
                        HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
                        //商品数量
                        int foodNum = (int) foodInfo.get("foodNum");
                        orderNumTotalNum = orderNumTotalNum + foodNum;
                        if (hcCompanyFoodList.getSalePrice() == null|| hcCompanyFoodList.getSalePrice().compareTo(new BigDecimal(0)) == 0) {
                            //获取门店价格
                            HcCompanyMerchantSetting companyMerchantSetting = hcCompanyMerchantSettingMapper.selectOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
                                    .eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
                                    .eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
                            if (null == companyMerchantSetting) {
                                companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
                            }
                            if (companyMerchantSetting.getSalePrice()==null||companyMerchantSetting.getSalePrice().compareTo(new BigDecimal(0)) == 0) {
                                //企业合作价格
                                orderNumFoodCost = orderNumFoodCost.add(hcCompanyInfo.getCompanyPrice().multiply(new BigDecimal(foodNum)));
                            } else {
                                orderNumFoodCost = orderNumFoodCost.add(companyMerchantSetting.getSalePrice().multiply(new BigDecimal(foodNum)));
                            }
                        } else {
                            orderNumFoodCost = orderNumFoodCost.add(hcCompanyFoodList.getSalePrice().multiply(new BigDecimal(foodNum)));
                        }
                        orderPrice = orderPrice.add(orderNumFoodCost);
                    }
                    departmentTotalNum = departmentTotalNum +orderNumTotalNum;
                    departmentTotalAmount = departmentTotalAmount.add(orderPrice);
                }
                //部门汇总
                cus.setTotalAmount(departmentTotalAmount);
                cus.setTotalOrder((long) departmentTotalNum);
                orderedMap.put(cus.toString(),cus);
            }
            totalOrder = totalOrder + departmentTotalNum;
            totalAmount = totalAmount.add(departmentTotalAmount);
        }
        //汇总对象
        CustomExportXlsTotalPojo cusTotal = new CustomExportXlsTotalPojo("汇总",totalOrder,totalAmount);
        orderedMap.put(cusTotal.toString(),cusTotal);
        List<CustomExportXlsTotalPojo> customExportXlsTotalPojos = new ArrayList<>(orderedMap.values());

        Row headerRow1 = sheet1.createRow(0);
        Set<String> sheet1Fields = sheet1FieldMap.keySet();
        int sheet1colNum = 0;

        for (String value : sheet1Fields) {
            Cell cell = headerRow1.createCell(sheet1colNum++);
            cell.setCellValue(sheet1FieldMap.get(value));
            cell.setCellStyle(chineseCellStyle); // 应用中文样式
        }
        //数据填充
        int rowNum1 = 1;
        for (CustomExportXlsTotalPojo pojo : customExportXlsTotalPojos) {
            //创建每行数据
            Row dataRow = sheet1.createRow(rowNum1++);
            // 设置序号列的值
            Cell counterCellData = dataRow.createCell(0);
            counterCellData.setCellStyle(dataCellStyle);
            //从第2列开始
            AtomicInteger cellNum = new AtomicInteger(0);
            //遍历属性，填充表格
            sheet1Fields.forEach(field -> {
                try {
                    Field studentField = CustomExportXlsTotalPojo.class.getDeclaredField(field.trim());
                    studentField.setAccessible(true);
                    Object o =studentField.get(pojo);
                    // 创建单元格并填充值
                    Cell cell = dataRow.createCell(cellNum.getAndIncrement());
                    cell.setCellValue(o != null ? o.toString() : "");
                    cell.setCellStyle(dataCellStyle); // 应用数据样式

                    // 自动调整列宽
                    sheet1.autoSizeColumn(cellNum.get() - 1);
                    // 获取自动调整后的列宽
                    int currentWidth = sheet.getColumnWidth(cellNum.get() - 1);

                    // 添加额外的字符宽度
                    int extraWidth = 100; // 设置额外的字符宽度
                    int finalWidth = currentWidth + extraWidth;

                    // 设置列宽
                    sheet1.setColumnWidth(cellNum.get() - 1, finalWidth);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }

        int month = DateUtils.getDate().getMonth()+1;
        String fileName;
        if (null != hcCompanyInfo){
            fileName = month +"月点餐菜品("+ hcCompanyInfo.getCompanyName()+") -反馈数据("+menuDisplayTime+")_"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
        }else {
            fileName = month + "月点餐菜品(无名) -反馈数据(" + menuDisplayTime + ")_" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
        }

        // 检查目录是否存在并具有写入权限
        File directory = new File(uploadpath);
        if (!directory.exists()) {
            System.out.println("目录不存在：" + uploadpath);
            if (directory.mkdirs()) {
                System.out.println("目录创建成功：" + uploadpath);
            } else {
                System.out.println("目录创建失败：" + uploadpath);
            }
        } else {
            System.out.println("目录存在：" + uploadpath);
        }

        // 保存文件
        try (FileOutputStream outputStream = new FileOutputStream(uploadpath+ File.separator+fileName)) {
            System.out.println(uploadpath+ File.separator+fileName);
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    @Override
    public HcMerchant getOrderStatistics(String merchantId, String companyId) {
        HcMerchant result = hcMerchantMapper.selectById(merchantId);
        List<HcOrderDetailed> orderDetailedList = new ArrayList<>();

        LambdaQueryWrapper<HcCompanyFoodOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getMerchantId, merchantId)
                .eq(HcCompanyFoodOrder::getCompanyId, companyId)
                .eq(HcCompanyFoodOrder::getState, HcOrderStateEnum.UNCOMPLETED);
        List<HcCompanyFoodOrder> companyFoodOrders = hcCompanyFoodOrderMapper.selectList(orderLambdaQueryWrapper).stream().filter(c -> !c.getState().equals(HcOrderStateEnum.CANCELED)).collect(Collectors.toList());
        for (HcCompanyFoodOrder order : companyFoodOrders) {
            JSONObject foodInfo = JSONObject.parseObject(order.getFoodInfo());
            //商品数量
            Integer foodNum = (Integer) foodInfo.get("foodNum");
            JSONObject foodObject = foodInfo.getJSONObject("food");
            HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);

            HcOrderDetailed h = new HcOrderDetailed();
            h.setTradeName(hcCompanyFoodList.getFoodName());
            h.setCommodityQuantity(foodNum);

            if (orderDetailedList.size() > 0) {
                boolean found = false;
                for (HcOrderDetailed hcOrderDetailed : orderDetailedList) {
                    if (hcOrderDetailed.getTradeName().equals(h.getTradeName())) {
                        hcOrderDetailed.setCommodityQuantity(hcOrderDetailed.getCommodityQuantity() + foodNum);
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    orderDetailedList.add(h);
                }
            } else {
                orderDetailedList.add(h);
            }
            result.setHcOrderDetailedList(orderDetailedList);
        }

        long count = hcCompanyFoodOrderMapper.selectList(new LambdaQueryWrapper<HcCompanyFoodOrder>()
                .eq(HcCompanyFoodOrder::getMerchantId, merchantId)
                .eq(HcCompanyFoodOrder::getCompanyId,companyId)
                .eq(HcCompanyFoodOrder::getState, HcOrderStateEnum.UNCOMPLETED)
                .eq(HcCompanyFoodOrder::getExportFlag, 0)).stream().filter(c -> !c.getState().equals(HcOrderStateEnum.CANCELED)).collect(Collectors.toList()).size();
        result.setNotExportedCount(count);
        return result;
    }

    @Override
    public HcCompanyFoodOrder getCompanyOrderLatest(String companyId) {
        HcCompanyFoodOrder order = hcCompanyFoodOrderMapper.selectOne(new LambdaQueryWrapper<HcCompanyFoodOrder>()
                .eq(HcCompanyFoodOrder::getCompanyId, companyId).orderByDesc(HcCompanyFoodOrder::getCreateTime)
                .last("limit 1"));
        return order;
    }

    @Override
    public List<HcMerchantData> getMerchantDataList(String merchantId, String companyId) throws ParseException {

        HcCompanyInfo hcCompanyInfo = hcCompanyInfoMapper.selectOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, companyId));
        List<HcMerchantData> result = new ArrayList<>();
        HcCompanyFoodOrder hcCompanyFoodOrder = hcCompanyFoodOrderMapper.getMixTime(merchantId, companyId);
        if (null!=hcCompanyFoodOrder){
            Calendar maxCalendar = Calendar.getInstance();
            Calendar minCalendar = Calendar.getInstance();
            minCalendar.setTime(hcCompanyFoodOrder.getMinDate());

            int d = DateUtils.dateDiff('d', DateUtils.parseCalendar(DateUtils.formatDate(maxCalendar, "yyyy-MM-dd"), "yyyy-MM-dd"), DateUtils.parseCalendar(DateUtils.formatDate(minCalendar, "yyyy-MM-dd"), "yyyy-MM-dd"));

            if (maxCalendar.getTime().after(DateUtils.parseDate(DateUtils.formatDate(maxCalendar, "yyyy-MM-dd") + " 18:00:00", "yyyy-MM-dd HH:mm:ss"))) {
                d++;
                maxCalendar.add(Calendar.DAY_OF_MONTH, 1);
            }

            if (minCalendar.getTime().before(DateUtils.parseDate(DateUtils.formatDate(minCalendar, "yyyy-MM-dd") + " 18:00:00", "yyyy-MM-dd HH:mm:ss"))) {
                d++;
            }

            for (int i = 0; i < d; i++) {
                String beginTime = "";
                String endTime = DateUtils.formatDate(maxCalendar, "yyyy-MM-dd") + " 18:00:00";

                Calendar instance = Calendar.getInstance();
                instance.setTime(maxCalendar.getTime());
                instance.add(Calendar.DAY_OF_MONTH, -1);
                beginTime = DateUtils.formatDate(instance, "yyyy-MM-dd") + " 18:00:01";
                HcMerchantData merchantDataRecord = new HcMerchantData();

                //今日收入
                List<HcCompanyFoodOrder> companyFoodOrderList = hcCompanyFoodOrderMapper.selectList(new LambdaQueryWrapper<HcCompanyFoodOrder>()
                        .eq(HcCompanyFoodOrder::getMerchantId, merchantId).eq(HcCompanyFoodOrder::getCompanyId, companyId)
//                        .eq(HcCompanyFoodOrder::getState, HcOrderStateEnum.COMPLETED)
                        .between(HcCompanyFoodOrder::getCreateTime, beginTime, endTime)).stream().filter(c -> !c.getState().equals(HcOrderStateEnum.CANCELED)).collect(Collectors.toList());

                List<String> orderNums = companyFoodOrderList.stream().map(HcCompanyFoodOrder::getOrderNum).distinct().collect(Collectors.toList());
                //有效订单
                merchantDataRecord.setEffectiveQuantity((long) orderNums.size());
                BigDecimal todayIncome = new BigDecimal("0");

                //根据订单区分
                for (String orderNum : orderNums) {
                    List<HcCompanyFoodOrder> companyFoodOrders = hcCompanyFoodOrderMapper.selectList(new LambdaQueryWrapper<HcCompanyFoodOrder>()
                            .eq(HcCompanyFoodOrder::getOrderNum, orderNum).eq(HcCompanyFoodOrder::getMerchantId,merchantId));

                    //过滤掉取消的订单
                    List<HcCompanyFoodOrder> foodOrderList = companyFoodOrders.stream().filter(c -> !c.getState().equals(HcOrderStateEnum.CANCELED)).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(foodOrderList)){
                        //价格
                        BigDecimal foodPrice = new BigDecimal(0);
                        BigDecimal totalPrice = new BigDecimal(0);
                        for (HcCompanyFoodOrder CompanyFoodOrder : foodOrderList) {
                            JSONObject foodInfo = JSONObject.parseObject(CompanyFoodOrder.getFoodInfo());
                            JSONObject foodObject = foodInfo.getJSONObject("food");
                            HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
                            //商品数量
                            int foodNum = (int) foodInfo.get("foodNum");
                            if (hcCompanyFoodList.getCooperatePrice()==null || hcCompanyFoodList.getCooperatePrice().compareTo(new BigDecimal(0)) == 0){
                                //获取门店价格
                                HcCompanyMerchantSetting companyMerchantSetting = hcCompanyMerchantSettingMapper.selectOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
                                        .eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
                                        .eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
                                if (null == companyMerchantSetting){
                                    companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
                                }
                                if (companyMerchantSetting.getMerchantCooperatePrice()==null||companyMerchantSetting.getMerchantCooperatePrice().compareTo(new BigDecimal(0))==0){
                                    //获取企业合作价格
                                    foodPrice = foodPrice.add(hcCompanyInfo.getMerchantPrice().multiply(new BigDecimal(foodNum)));
                                }else {
                                    foodPrice = foodPrice.add(companyMerchantSetting.getMerchantCooperatePrice().multiply(new BigDecimal(foodNum)));
                                }
                            }else {
                                foodPrice = foodPrice.add(hcCompanyFoodList.getCooperatePrice().multiply(new BigDecimal(foodNum)));
                            }
//                            totalPrice = totalPrice.add(foodPrice);
                        }
                        todayIncome = todayIncome.add(foodPrice);
                    }
                }

                merchantDataRecord.setDateStr(DateUtils.formatDate(maxCalendar, "yyyy年MM月dd日"));
                List<HcCompanyMerchantSettlement> hcCompanyMerchantSettlementList = hcCompanyMerchantSettlementMapper.selectList(new LambdaQueryWrapper<HcCompanyMerchantSettlement>()
                        .eq(HcCompanyMerchantSettlement::getMerchantId, merchantId)
                        .eq(HcCompanyMerchantSettlement::getCompanyId,companyId)
                        .eq(HcCompanyMerchantSettlement::getType, HcMerchantSettlementTypeEnum.CHANGE)
                        .between(HcCompanyMerchantSettlement::getCreateTime, beginTime, endTime));

                List<HcMerchantSettlement> hcMerchantSettlementList = new ArrayList<>();
                final BigDecimal[] change = {new BigDecimal(0)};
                for (HcCompanyMerchantSettlement hcCompanyMerchantSettlement : hcCompanyMerchantSettlementList) {
                    HcMerchantSettlement hcMerchantSettlement =new HcMerchantSettlement();
                    BeanUtils.copyProperties(hcCompanyMerchantSettlement,hcMerchantSettlement);
                    hcMerchantSettlementList.add(hcMerchantSettlement);

                    change[0] = change[0].add(hcCompanyMerchantSettlement.getSettlementAmount());
                }
                //今日收入
                merchantDataRecord.setTodayIncome(todayIncome.add(change[0]));

                HcCompanyMerchantSettlement one = hcCompanyMerchantSettlementMapper.selectOne(new LambdaQueryWrapper<HcCompanyMerchantSettlement>()
                        .eq(HcCompanyMerchantSettlement::getMerchantId, merchantId)
                        .eq(HcCompanyMerchantSettlement::getCompanyId,companyId)
                        .eq(HcCompanyMerchantSettlement::getType, HcMerchantSettlementTypeEnum.SETTLED)
                        .eq(HcCompanyMerchantSettlement::getSettlementDate, DateUtils.formatDate(maxCalendar, "yyyy-MM-dd"))
                );

                if (one != null) {
                    merchantDataRecord.setSettlementType(one.getType());
                }
                merchantDataRecord.setHcMerchantSettlementList(hcMerchantSettlementList);
                result.add(merchantDataRecord);
                maxCalendar.add(Calendar.DAY_OF_MONTH, -1);
            }
        }

        return result;
    }

    @Override
    public ModelAndView platformExportXls(HcCompanyFoodOrder hcCompanyFoodOrder) {

        LambdaQueryWrapper<HcCompanyFoodOrder> hcCompanyFoodOrderLambdaQueryWrapper = new LambdaQueryWrapper<HcCompanyFoodOrder>();
        if (StringUtils.isNotBlank(hcCompanyFoodOrder.getTimeBegin()) && hcCompanyFoodOrder.getTimeBegin().length() == 16) {
            hcCompanyFoodOrder.setTimeBegin(hcCompanyFoodOrder.getTimeBegin() + ":00");
            hcCompanyFoodOrderLambdaQueryWrapper.ge(HcCompanyFoodOrder::getCreateTime,hcCompanyFoodOrder.getTimeBegin());
        }
        if (StringUtils.isNotBlank(hcCompanyFoodOrder.getTimeEnd()) && hcCompanyFoodOrder.getTimeEnd().length() == 16) {
            hcCompanyFoodOrder.setTimeEnd(hcCompanyFoodOrder.getTimeEnd() + ":00");
            hcCompanyFoodOrderLambdaQueryWrapper.le(HcCompanyFoodOrder::getCreateTime,hcCompanyFoodOrder.getTimeEnd());
        }
//		LambdaQueryWrapper<HcCompanyFoodOrder> hcCompanyFoodOrderLambdaQueryWrapper = new LambdaQueryWrapper<HcCompanyFoodOrder>();
//				.between(HcCompanyFoodOrder::getCreateTime, hcCompanyFoodOrder.getTimeBegin() + ":00", hcCompanyFoodOrder.getTimeEnd() + ":00");
        if (StringUtils.isNotBlank(hcCompanyFoodOrder.getMerchantId())){
            hcCompanyFoodOrderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getMerchantId,hcCompanyFoodOrder.getMerchantId());
        }
        if (StringUtils.isNotBlank(hcCompanyFoodOrder.getCompanyId())){
            hcCompanyFoodOrderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getCompanyId,hcCompanyFoodOrder.getCompanyId());
        }
        if (StringUtils.isNotBlank(hcCompanyFoodOrder.getStoreName())){
            hcCompanyFoodOrderLambdaQueryWrapper.like(HcCompanyFoodOrder::getUsername,hcCompanyFoodOrder.getStoreName()).or()
                    .like(HcCompanyFoodOrder::getPickingSerialNo,hcCompanyFoodOrder.getStoreName()).or()
                    .like(HcCompanyFoodOrder::getFoodInfo,hcCompanyFoodOrder.getStoreName());
        }
        if (StringUtils.isNotBlank(hcCompanyFoodOrder.getSelections())) {
            List<String> orders = Arrays.asList(hcCompanyFoodOrder.getSelections().split(","));
            hcCompanyFoodOrderLambdaQueryWrapper.in(HcCompanyFoodOrder::getOrderNum,orders);
        }
        List<HcCompanyFoodOrder> list = hcCompanyFoodOrderMapper.selectList(hcCompanyFoodOrderLambdaQueryWrapper.orderByDesc(HcCompanyFoodOrder::getCreateTime));

        //获取企业订单信息
        List<String> orderNumList = list.stream().map(HcCompanyFoodOrder::getOrderNum).distinct().collect(Collectors.toList());

        List<HcOrderMerchant> companyOrder = new ArrayList<>();
        for (String orderNum : orderNumList) {
            HcOrderMerchant h = new HcOrderMerchant();
            h.setId(orderNum);
            List<HcOrderDetailed> hcOrderDetailedLists = new ArrayList<>();
            List<HcCompanyFoodOrder> companyFoodOrders = hcCompanyFoodOrderMapper.selectList(new LambdaQueryWrapper<HcCompanyFoodOrder>().eq(HcCompanyFoodOrder::getOrderNum, orderNum));
            HcCompanyInfo hcCompanyInfo = hcCompanyInfoService.getOne(new LambdaQueryWrapper<HcCompanyInfo>().eq(HcCompanyInfo::getId, companyFoodOrders.get(0).getCompanyId()));
            h.setCompanyName(hcCompanyInfo.getCompanyName());

            HcOrderDetailed hcOrderDetailed = new HcOrderDetailed();
            List<String> foodName = new ArrayList<>();
            //价格
            BigDecimal foodPrice = new BigDecimal(0);
            //合作价格
            BigDecimal coopPrice = new BigDecimal(0);
            for (HcCompanyFoodOrder hcfo : companyFoodOrders) {
                h.setState(hcfo.getState());

                HcMerchant hcMerchant = hcMerchantService.getOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getId,hcfo.getMerchantId()));
                h.setStoreName(hcMerchant.getStoreName());
                h.setMerchantId(hcfo.getMerchantId());
                h.setCreateTime(hcfo.getCreateTime());
                //地址
                String pickupAddressId = hcfo.getPickupAddressId();
                HcCompanyPickupAddress pickupAddress = hcCompanyPickupAddressService.getOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, pickupAddressId));
                if (null != pickupAddress){
                    h.setSupplyAddress(pickupAddress.getAddressCode());
                }

                //取餐号
                h.setPickingSerialNo(hcfo.getPickingSerialNo());
                h.setNameTakingMeal(hcfo.getUsername());
                JSONObject foodInfo = JSONObject.parseObject(hcfo.getFoodInfo());
                JSONObject foodObject = foodInfo.getJSONObject("food");
                HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
                //商品数量
                int foodNum = (int) foodInfo.get("foodNum");
                // 获取 foodsSpecification 列表
                JSONArray foodsSpecificationArray = foodInfo.getJSONArray("foodsSpecification");
                // 将 JSONArray 转换为 List<String>
                List<HcCompanyFoodSpecifications> foodsSpecificationList = new ArrayList<>();
                if (foodsSpecificationArray!=null){
                    foodsSpecificationList = foodsSpecificationArray.toJavaList(HcCompanyFoodSpecifications.class);
                    List<String> collect = foodsSpecificationList.stream().map(f -> f.getSpecificationName()).collect(Collectors.toList());
                    foodName.add(hcCompanyFoodList.getFoodName()+"("+Joiner.on(",").join(collect) +") x"+ foodNum);
                }else {
                    foodName.add(hcCompanyFoodList.getFoodName()+"x"+ foodNum);
                }
                if (hcCompanyFoodList.getCooperatePrice()==null||hcCompanyFoodList.getCooperatePrice().compareTo(new BigDecimal(0)) == 0){
                    //获取门店价格
                    HcCompanyMerchantSetting companyMerchantSetting = hcCompanyMerchantSettingMapper.selectOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
                            .eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
                            .eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
                    if (null == companyMerchantSetting){
                        companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
                    }
                    if (companyMerchantSetting.getMerchantCooperatePrice()==null||companyMerchantSetting.getMerchantCooperatePrice().compareTo(new BigDecimal(0))==0){
                        //获取企业合作价格
                        foodPrice = foodPrice.add(hcCompanyInfo.getMerchantPrice());
                    }else {
                        foodPrice = foodPrice.add(companyMerchantSetting.getMerchantCooperatePrice());
                    }
                }else {
                    foodPrice = foodPrice.add(hcCompanyFoodList.getCooperatePrice());
                }
                if (hcCompanyFoodList.getSalePrice()==null||hcCompanyFoodList.getSalePrice().compareTo(new BigDecimal(0)) == 0){
                    //获取门店价格
                    HcCompanyMerchantSetting companyMerchantSetting = hcCompanyMerchantSettingMapper.selectOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
                            .eq(HcCompanyMerchantSetting::getCompanyId, hcCompanyFoodList.getCompanyId())
                            .eq(HcCompanyMerchantSetting::getMerchantId, hcCompanyFoodList.getMerchantId()));
                    if (null == companyMerchantSetting){
                        companyMerchantSetting = new HcCompanyMerchantSetting().setMerchantCooperatePrice(new BigDecimal(0)).setSalePrice(new BigDecimal(0));
                    }
                    if (companyMerchantSetting.getSalePrice()==null||companyMerchantSetting.getSalePrice().compareTo(new BigDecimal(0))==0){
                        //获取企业合作价格
                        coopPrice = coopPrice.add(hcCompanyInfo.getCompanyPrice().multiply(new BigDecimal(foodNum)));
                    }else {
                        coopPrice = coopPrice.add(companyMerchantSetting.getSalePrice().multiply(new BigDecimal(foodNum)));
                    }
                }else {
                    coopPrice = coopPrice.add(hcCompanyFoodList.getSalePrice().multiply(new BigDecimal(foodNum)));
                }
            }

            hcOrderDetailed.setTradeName(Joiner.on("+").join(foodName));
            h.setNameDishes(Joiner.on("+").join(foodName));
            hcOrderDetailedLists.add(hcOrderDetailed);
            h.setCommodityPrice(foodPrice);
            h.setTotalPrice(coopPrice);
            h.setHcOrderDetailedList(hcOrderDetailedLists);
            companyOrder.add(h);
        }
        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.CLASS, HcOrderMerchant.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams();
        exportParams.setImageBasePath(uploadpath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, companyOrder);

        return mv;

    }

    @Transactional(rollbackFor = Exception.class)
    public String exportXls(String merchantId,String companyId, List<String> ids, String type) {
        HcMerchant hcMerchant = hcMerchantService.getById(merchantId);
        List<HcOrderMerchantExport> exportList = new ArrayList<>();
        LambdaQueryWrapper<HcCompanyFoodOrder> hcCompanyFoodOrderLambdaQueryWrapper = new LambdaQueryWrapper<HcCompanyFoodOrder>();

        if (StringUtils.isNotBlank(merchantId)){
            hcCompanyFoodOrderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getMerchantId,merchantId);
        }
        if (StringUtils.isNotBlank(companyId)){
            hcCompanyFoodOrderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getCompanyId,companyId);
        }
        if ("merchant".equals(type)||CollectionUtils.isEmpty(ids)){
            hcCompanyFoodOrderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getExportFlag,0);
        }
        if (CollectionUtils.isNotEmpty(ids)){
            hcCompanyFoodOrderLambdaQueryWrapper.in(HcCompanyFoodOrder::getId,ids);
        }
        List<HcCompanyFoodOrder> list = hcCompanyFoodOrderMapper
                .selectList(hcCompanyFoodOrderLambdaQueryWrapper
                        .eq(HcCompanyFoodOrder::getState, HcOrderStateEnum.UNCOMPLETED)
                        .orderByDesc(HcCompanyFoodOrder::getCreateTime));

        //获取企业订单信息
        List<String> orderNumList = list.stream().map(HcCompanyFoodOrder::getOrderNum).distinct().collect(Collectors.toList());
        for (String orderNum : orderNumList) {
            List<HcOrderDetailed> hcOrderDetailedLists = new ArrayList<>();
            LambdaQueryWrapper<HcCompanyFoodOrder> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderLambdaQueryWrapper.eq(HcCompanyFoodOrder::getOrderNum, orderNum).eq(HcCompanyFoodOrder::getMerchantId,merchantId);
            if (CollectionUtils.isNotEmpty(ids)) {
                orderLambdaQueryWrapper.in(HcCompanyFoodOrder::getId,ids);
            }
            List<HcCompanyFoodOrder> companyFoodOrders = hcCompanyFoodOrderMapper.selectList(orderLambdaQueryWrapper);

            List<String> allFoodName = new ArrayList<>();
            for (HcCompanyFoodOrder hcfo : companyFoodOrders) {
                List<String> foodName = new ArrayList<>();
                HcOrderMerchantExport h = new HcOrderMerchantExport();
                h.setId(hcfo.getId());
                HcOrderDetailed hcOrderDetailed = new HcOrderDetailed();
                //地址
                String pickupAddressId = hcfo.getPickupAddressId();
                HcCompanyPickupAddress pickupAddress = hcCompanyPickupAddressService.getOne(new LambdaQueryWrapper<HcCompanyPickupAddress>().eq(HcCompanyPickupAddress::getId, pickupAddressId));
                if (null != pickupAddress){
                    h.setSupplyAddress(pickupAddress.getAddressCode());
                }
                //取餐号
                h.setPickingSerialNo(hcfo.getPickingSerialNo());
                h.setNameTakingMeal(hcfo.getUsername());
                JSONObject foodInfo = JSONObject.parseObject(hcfo.getFoodInfo());
                JSONObject foodObject = foodInfo.getJSONObject("food");
                HcCompanyFoodList hcCompanyFoodList = foodObject.toJavaObject(HcCompanyFoodList.class);
                //商品数量
                int foodNum = (int) foodInfo.get("foodNum");
                // 获取 foodsSpecification 列表
                JSONArray foodsSpecificationArray = foodInfo.getJSONArray("foodsSpecification");
                // 将 JSONArray 转换为 List<String>
                List<HcCompanyFoodSpecifications> foodsSpecificationList = new ArrayList<>();
                if (foodsSpecificationArray!=null){
                    foodsSpecificationList = foodsSpecificationArray.toJavaList(HcCompanyFoodSpecifications.class);
                    List<String> collect = foodsSpecificationList.stream().map(f -> f.getSpecificationName()).collect(Collectors.toList());
                    foodName.add(hcCompanyFoodList.getFoodName()+"("+Joiner.on(",").join(collect) +") x"+ foodNum);
                }else {
                    foodName.add(hcCompanyFoodList.getFoodName()+"x"+ foodNum);
                }
                hcOrderDetailed.setTradeName(Joiner.on("+").join(foodName));
                h.setNameDishes(Joiner.on("+").join(foodName));
                hcOrderDetailedLists.add(hcOrderDetailed);
                h.setRemarks(hcfo.getRemark());
                allFoodName.addAll(foodName);
                exportList.add(h);
            }
            if ("merchant".equals(type)||CollectionUtils.isEmpty(ids)) {
                hcCompanyFoodOrderMapper.updateByOrderNum(orderNum,merchantId);
            }
        }

        List<HcOrderMerchantExport> sortList = exportList.stream().sorted(Comparator.comparing(HcOrderMerchantExport::getNameDishes, (x, y) -> {
            Collator clt = Collator.getInstance(Locale.CHINA);
            return clt.compare(x, y);
        })).collect(Collectors.toList());

        // Step.3 AutoPoi 导出Excel
        ExportParams exportParams = new ExportParams();
        exportParams.setImageBasePath(uploadpath);

        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, HcOrderMerchantExport.class, sortList);
        MultipartFile multipartFile = HcUtils.workbookToCommonsMultipartFile(sheets, hcMerchant.getStoreName() + DateUtils.formatDate(new Date(), "yyyy-MM-dd-HH-mm") + ".xls");
        return CommonUtils.upload(multipartFile, "exportExcel", "alioss");
    }


    @Override
    public void updateByOrderNum() {
        hcCompanyFoodOrderMapper.updateOrder2Finished();
    }


}
